import axios, { Method, AxiosInstance, AxiosRequestConfig } from 'axios';
import { InterceptorV2, getConfigHeadrs } from './http.interceptor';

interface IHttpMethodsProps {
    request: (
        method: Method,
        url: string,
        params: object,
        headers?: object,
    ) => Promise<any>;
    get: (url: string, params: object, headers?: object) => Promise<any>;
    post: (url: string, params: object, headers?: object) => Promise<any>;
}

/** http请求封装类 */
class HttpServer implements IHttpMethodsProps {
    /** 请求实例 */
    public serverInstance: AxiosInstance;
    public serverStack: Array<AxiosRequestConfig>;
    constructor(timeout: number = 10000) {
        this.serverStack = [];
        this.serverInstance = axios.create({
            timeout,
        });
        /** 拦截器 */
        InterceptorV2(this.serverInstance, this.serverStack);
    }
    /** request请求 */
    request(method: Method, url: string, params: object = {}, headers?: object) {
        return new Promise((resolve, reject) => {
            method = method.toLocaleUpperCase() as Method;
            const httpConfig = method === 'GET' ? { params } : { data: params };
            Object.assign(httpConfig, {
                method,
                url,
                headers: getConfigHeadrs(headers),
            });
            this.serverInstance(httpConfig)
                .then((response) => {
                    if (response) {
                        const { data, status } = response;
                        if (data && status === 200) {
                            resolve(data);
                        } else {
                            reject('网络请求失败');
                        }
                    } else {
                        reject('系统错误');
                    }
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
    /** get请求 */
    get(url: string, params: object = {}, headers?: object) {
        return this.request('GET', url, params, headers);
    }
    /** post请求 */
    post(url: string, params: object = {}, headers?: object) {
        return this.request('POST', url, params, headers);
    }
}

export default new HttpServer();
